#!/usr/bin/env bash

############################################################
# https://docs.docker.com/engine/install/centos/
# https://docs.docker.com/compose/install/linux/
# https://github.com/docker/buildx/releases
# 在线安装docker-ce
# 阿里云内网：http://mirrors.cloud.aliyuncs.com
# 阿里云外网：https://mirrors.aliyun.com
############################################################

set -e

# 数据存储目录，默认为/var/lib/docker
declare -r DOCKER_ROOT_DIR="/var/lib/docker"
# 私有仓库Harbor地址(如果不配置则留空)
declare -r PRIVATE_REGISTRY=""
# 自定义容器网段, Docker默认的容器网段为：172.17.0.0/16，如何存在网段冲突，则进行修改，比如：192.168.66.1/24, 否则留空
declare -r DOCKER_NETWORK=""
# 镜像加速器地址(阿里，华为, 腾讯)，应该只能在对应的公有云ECS中使用，不配置的话则留空
# 阿里：https://ypa4a2su.mirror.aliyuncs.com
# 腾讯：https://mirror.ccs.tencentyun.com
# 华为：https://066d226825000fab0faac00f863afee0.mirror.swr.myhuaweicloud.com
declare -r REGISTRY_MIRRORS="https://mirror.ccs.tencentyun.com"
# 获取操作系统(centos, alinux, ubuntu, debian, hce, openEuler)
# shellcheck disable=SC1091
ID=$(source /etc/os-release && echo "${ID//\"}")
# 获取版本号
# shellcheck disable=SC1091
VERSION_ID=$(source /etc/os-release && echo "${VERSION_ID//\"}")

DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$DIR" || exit 1

### 日志函数
log_info()    { echo -e "\033[34m[INFO] $*\033[0m"; }
log_warn()    { echo -e "\033[33m[WARNING] $*\033[0m"; }
log_success() { echo -e "\033[32m[SUCCESS] $*\033[0m"; }
log_error()   { echo -e "\033[31m[ERROR] $*\033[0m"; exit 1; }

### 阿里云 alinux， 服务器在阿里云
install_docker_alinux() {
    log_info "安装docker-ce"
    sudo wget -O /etc/yum.repos.d/docker-ce.repo http://mirrors.cloud.aliyuncs.com/docker-ce/linux/centos/docker-ce.repo
    sudo sed -i 's|https://mirrors.aliyun.com|http://mirrors.cloud.aliyuncs.com|g' /etc/yum.repos.d/docker-ce.repo
    # Alibaba Cloud Linux 3
    if [ "$VERSION_ID" -eq 3 ]; then
        sudo dnf -y install dnf-plugin-releasever-adapter --repo alinux3-plus
        sudo dnf -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
    # Alibaba Cloud Linux 2
    else
        sudo yum -y install yum-plugin-releasever-adapter --disablerepo=* --enablerepo=plus
        sudo yum -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
    fi
}
### Centos 7.x, Centos 8.x, fedora, Red Hat, almalinux
install_docker_redhat() {
    local cmd=""
    if command -v dnf &>/dev/null; then
        cmd="dnf"
    else
        cmd="yum"
    fi
    log_info "安装docker-ce"

    # id=fedora 或 id=centos 或 id=rhel 或 almalinux
    if [ "$ID" = "fedora" ]; then
        sudo wget -O /etc/yum.repos.d/docker-ce.repo https://mirrors.aliyun.com/docker-ce/linux/"$ID"/docker-ce.repo
    else
        sudo wget -O /etc/yum.repos.d/docker-ce.repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    fi
    # sudo sed -i 's|https://mirrors.aliyun.com|http://mirrors.cloud.aliyuncs.com|g' /etc/yum.repos.d/docker-ce.repo
    sudo $cmd -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
}
### Ubuntu 和 Debian
install_docker_ubuntu_debian() {
    log_info "安装docker-ce"
    sudo apt-get update
    sudo apt-get -y install apt-transport-https ca-certificates curl software-properties-common
    sudo curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/"$ID"/gpg | sudo apt-key add -
    sudo add-apt-repository -y "deb [arch=$(dpkg --print-architecture)] https://mirrors.aliyun.com/docker-ce/linux/$ID $(lsb_release -cs) stable"
    sudo apt-get -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
}
### TencentOS Server 3和4，服务器在腾讯云
install_docker_tencentos() {
    log_info "安装docker"
    local cmd=""
    if command -v dnf &>/dev/null; then
        cmd="dnf"
    else
        cmd="yum"
    fi
    local version_id=""
    version_id=$(echo "$VERSION_ID"|awk -F'.' '{print $1}')
    if [ "$version_id" -eq 4 ]; then
        # TencentOS Server 4.+
        # 安装腾讯预置的docker, 无docker-buildx和docker-compose-plugin
        sudo $cmd install -y docker
        sudo $cmd install -y docker-buildx-plugin docker-compose-plugin
        # 使用这个命令也能直接安装社区版的docker-ce
        # sudo $cmd install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
    else
        # TencentOS Server 3.+
        sudo $cmd install -y docker-ce docker-buildx-plugin docker-compose-plugin
    fi
}
### opencloudos
install_docker_opencloudos() {
    log_info "安装docker"
    local cmd=""
    if command -v dnf &>/dev/null; then
        cmd="dnf"
    else
        cmd="yum"
    fi
    local version_id=""
    version_id=$(echo "$VERSION_ID"|awk -F'.' '{print $1}')
    if [ "$version_id" -eq 9 ]; then
        sudo $cmd install -y docker docker-buildx-plugin docker-compose-plugin
    else
        sudo $cmd config-manager --add-repo=https://mirrors.cloud.tencent.com/docker-ce/linux/centos/docker-ce.repo
        sudo sed -i "s/download.docker.com/mirrors.tencentyun.com\/docker-ce/g"  /etc/yum.repos.d/docker-ce.repo
        sudo $cmd install -y docker-ce docker-buildx-plugin docker-compose-plugin
    fi
}

### Huawei Cloud EulerOS
install_docker_huawei() {
    log_warn "华为的EulerOS或openEuler默认安装docker-engine:18.09.0，不建议使用此版本，请采用离线安装方式!"
}
### Anolis OS
install_docker_anolis() {
    local cmd=""
    if command -v dnf &>/dev/null; then
        cmd="dnf"
    else
        cmd="yum"
    fi
    log_info "安装docker-ce"
    sudo wget -O /etc/yum.repos.d/docker-ce.repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    # sudo sed -i 's|https://mirrors.aliyun.com|http://mirrors.cloud.aliyuncs.com|g' /etc/yum.repos.d/docker-ce.repo
    sudo $cmd -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
}

### 安装Docker-CE
install_docker_ce() {

    log_info "添加/etc/docker/daemon.json文件"
    [ ! -d "/etc/docker" ] && sudo mkdir -p /etc/docker
    local data_root_line=""
    if [ "$DOCKER_ROOT_DIR" != "/var/lib/docker" ]; then
        data_root_line="\"data-root\": \"$DOCKER_ROOT_DIR\","
    fi
    local private_registry=""
    if [ -n "$PRIVATE_REGISTRY" ]; then
        private_registry="\"insecure-registries\": [\"${PRIVATE_REGISTRY}\"],"
    fi
    local registry_mirrors=""
    if [ -n "$REGISTRY_MIRRORS" ]; then
        registry_mirrors="\"registry-mirrors\": [\"${REGISTRY_MIRRORS}\"],"
    fi
    local docker_network=""
    if [ -n "$DOCKER_NETWORK" ]; then
        docker_network="\"bip\": \"$DOCKER_NETWORK\","
    fi
    
sudo tee /etc/docker/daemon.json << EOF
{
    ${private_registry}
    ${registry_mirrors}
    ${data_root_line}
    ${docker_network}
    "log-driver": "json-file",
    "log-opts": {
      "max-size": "20m",
      "max-file": "10"
    }
}
EOF

    # 删除/etc/docker/daemon.json里的空行
    log_info "删除/etc/docker/daemon.json里的空行"
    sudo sed -i '/^\s*$/d' /etc/docker/daemon.json

    # 安装docker
    case "$ID" in
        alinux)
            install_docker_alinux
        ;;
        anolis)
            install_docker_anolis
        ;;
        tencentos)
            install_docker_tencentos
        ;;
        opencloudos)
            install_docker_opencloudos
        ;;
        centos|fedora|rhel|almalinux)
            install_docker_redhat
        ;;
        openEuler|hce)
            install_docker_huawei
            exit 1
        ;;
        ubuntu|debian)
            install_docker_ubuntu_debian ;;
        *)
            log_error "不支持的操作系统: $ID"
        ;;
    esac

    if [ -f "/etc/sysconfig/docker" ]; then
        log_info "修改/etc/sysconfig/docker文件"
        sudo sed -i '/log-driver/d' /etc/sysconfig/docker
    fi
    
    log_info "启动docker服务"
    sudo systemctl enable docker
    sudo systemctl start docker
}

main() {

    if command -v docker &>/dev/null; then
        log_error "docker已安装, 请勿重复安装"
    fi

    # # rhel系列的系统
    # if [ "$(getenforce)" = "Enforcing" ]; then
    #     log_info "调整SELinux为Permissive模式"
    #     setenforce 0
    #     sudo sed -i -r "/^SELINUX=/c SELINUX=disabled" /etc/selinux/config
    # fi
    
    # 基于Red Hat的发行版
    if command -v getenforce &>/dev/null; then
        current_mode="$(getenforce)"
        if [ "$current_mode" = "Enforcing" ]; then
            log_info "调整SELinux为Permissive模式"
            sudo setenforce 0
        else
            log_info "SELinux 当前模式为 $current_mode，无需调整"
        fi

        if grep '^SELINUX=enforcing$' /etc/selinux/config >/dev/null 2>&1; then
            log_info "调整SELinux模式为permissive"
            sudo sed -i 's/^SELINUX=enforcing$/SELINUX=permissive/' /etc/selinux/config
        fi
    fi

    if [[ $(sudo sysctl -n net.ipv4.ip_forward) -eq 0 ]]; then
        log_info "设置net.ipv4.ip_forward=1"
        if grep -q 'net.ipv4.ip_forward' /etc/sysctl.conf; then
            sudo sed -i "/^net.ipv4.ip_forward/c net.ipv4.ip_forward = 1" /etc/sysctl.conf
        else
            sudo sh -c "echo 'net.ipv4.ip_forward = 1' >> /etc/sysctl.conf"
        fi
        sudo sysctl -p
    fi

    install_docker_ce

    if [ -f "/usr/libexec/docker/cli-plugins/docker-compose" ]; then
        sudo ln -sfn /usr/libexec/docker/cli-plugins/docker-compose /usr/bin/docker-compose
    fi

    log_info "docker版本：$(docker --version)"
    
    # 清理旧版本
    # sudo dnf -y remove \
    #     docker-ce \
    #     containerd.io \
    #     docker-ce-rootless-extras \
    #     docker-buildx-plugin \
    #     docker-ce-cli \
    #     docker-compose-plugin

    # 清理旧版本（openEuler和Euler）
    # dnf remove docker \
    #     docker-client \
    #     docker-client-latest \
    #     docker-common \
    #     docker-latest \
    #     docker-latest-logrotate \
    #     docker-logrotate \
    #     docker-engine

    # 清理旧版本
    # for pkg in docker.io docker-buildx-plugin docker-ce-cli docker-ce-rootless-extras docker-compose-plugin docker-doc docker-compose podman-docker containerd runc;do sudo apt-get remove -y $pkg; done
}

main "$@"